Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

157
Visualizações
Why is my line not breaking when I use "\n" in react?

I am trying to use this hook:

useEffect(() => {
  var arrText = txt.split('*');
  arrText.map((line, index) =>
    setTimeout(() => {
      setTexto((prev) => {
        return (prev += line + '\n');
      });
    }, 300 * index),
  );
}, []);

And it simply rejects my \n and if I try to return JSX (the line in a paragraph), it becomes a [object object]

Can you please help me? <3

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The problem is, unless you're trying to display a newline in a pre tag, it will be ignored in the browser. You could however store the text content in the state in an array, update that using the setTimeout and render this state. You can use <p> tags or <br> tags to display the text on new lines.

Also, you shouldn't use map() as it creates a new array. You could use forEach() or a simple for loop instead.

let txt =
  'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Tenetur sapiente incidunt molestias beatae voluptas fuga repellendus sit nihil voluptate laudantium delectus aliquam, nulla non suscipit a ea natus voluptatem distinctio!';

function App() {
  let [texto, setTexto] = React.useState([]);

  React.useEffect(() => {
    txt.split(' ').forEach((line, index) =>
      setTimeout(() => {
        setTexto((prev) => {
          return [...prev, line];
        });
      }, 300 * index)
    );
  }, []);

  return (
    <div>
      {texto.map((word, i) => (
        <p key={i}>{word}</p>
      ))}
    </div>
  );
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);
<div id="root"></div>
<script src="https://unpkg.com/react/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.production.min.js"></script>

You shouldn't store HTML tags in your state as you will need to use dangerouslySetInnerHTML.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda